package com.afb

import com.afb.HHPredJob
import java.io.ByteArrayInputStream;

import java.io.InputStream;
import org.biojava.bio.*;
import org.biojava.bio.seq.Sequence;
import org.biojava.bio.seq.SequenceIterator;
import org.biojava.bio.seq.db.*;
import org.biojava.bio.seq.io.*;
import org.biojava.bio.symbol.*;

import org.codehaus.groovy.grails.web.context.ServletContextHolder as SCH


class PredService implements Processable {

    boolean transactional = true

    // Vou so por como chave o id do processos e como valor a path para o ficheiro... Nao da que assim n tenho critério para organizar...
    def PATH_TO_FILE = ""

    def MAX_NUMBER_OF_PROCESS = 10;

    StringBuffer sb = new StringBuffer();

    def servletContext = SCH.servletContext

//    String PATH_TO_TEMP_FILES_DIRECTORY = SCH.servletContext.getRealPath("/")

    String PATH_TO_TEMP_FILES_DIRECTORY

    public static final String PROCESSED_FILES_EXTENSION = "hhr"
    public static final String RUNNING_FILES_EXTENSION = "fasta"

//    public static final String PATH_TO_HMM_DATABASE = "D:\\programas\\hhsearch1.5.1.1\\scop70_1.75.hhm"
public static final String PATH_TO_HMM_DATABASE = "/home/cris/Databases/SCOP/scop70_1.75.hhm"


    public void metodoQualquer() {
        println " Vou executar o metodoQualquer";
    }


    def getFileName(Process p) {
        String nomeTempFile = PATH_TO_TEMP_FILES_DIRECTORY + p.job.user.id+"_"+p.job.id+"_"+p.id;
        return nomeTempFile;
    }


    def serviceMethod() {
    }

    def createQueuedProcess(Process proc) {
        sb.append(proc.id);
        sb.append("|");
        sb.append("|");

    }


    def stringToInputStream(String text) {
        try {
            InputStream is = new ByteArrayInputStream(text.getBytes("UTF-8"));
            return is;
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }


    def addProcesses(HHPredJob job) {


        def processos;

        BufferedInputStream is =
        new BufferedInputStream(new ByteArrayInputStream(job.proteinSequences.getBytes("UTF-8")));

        //get the appropriate Alphabet
        //      Alphabet alpha = AlphabetManager.alphabetForName(args[1]);
        Alphabet alpha = AlphabetManager.alphabetForName("PROTEIN");

        //get a SequenceDB of all sequences in the file
        SequenceDB db = SeqIOTools.readFasta(is, alpha);

        SequenceIterator si = db.sequenceIterator();
        StringBuilder  str;
        def seqHeader;

        if (servletContext.QueuedJobs==null) {
            servletContext.QueuedJobs = [:]
        }

        // total de processos pendentes por Job
        if (servletContext.runningProcesses == null) {
            servletContext.runningProcesses = [:]
        }


        int numeroProcessos = 0;
        while ((si.hasNext())) {

            Sequence seq = si.nextSequence();

            seqHeader = seq.getAnnotation().toString();

            CharSequence titulo = seqHeader.subSequence(18, seqHeader.indexOf('}'));

            str = new StringBuilder();
            str.append(">");

            str.append(titulo);
            str.append("\n");
            str.append(""+seq.seqString());
            str.append("\n");

            processos = new Process();
            processos.name = job.name+"_"+numeroProcessos;
            processos.description = titulo;
            processos.input = str.toString();
            processos.output="";
//            processos.started=false;
//            processos.finished=false;
            processos.status = "queued"
            processos.job = job;
            if (processos.save(flush: true)) {
                println("processo criado !!! ");
                println(""+processos.input);
            } else {
                println("falha na criação do processo...");
                    processos.errors.allErrors.each {
                        println it
                    }
            }

//            servletContext.queuedProcesses["proc "+processos.id] = "proc "+processos.id;
            numeroProcessos++;


            println "sera que aki tb ?!? " +servletContext.texte
            println ">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> números de processos : "+ Process.count()
        }

        servletContext.isListOfProcessesAltered = true;
        servletContext.isAvailableToProcess = true;
//        servletContext.jobQueuedProcess[job.id] = numeroProcessos;

        println "pppppppppppppptetsadfsadfasdfasdfasdfasfddddddddddddddddddddddddddddddddddddfkjsdhakfjhasdkfjhsdakfjhsdakfjhasdkfjs"
        println "jobsds : " + Process.findAllByJob(job)
        println "lsita de jobs : " + Process.list()

    }





    def cleanPossibleCreatedFiles(Process proc) {

            PATH_TO_TEMP_FILES_DIRECTORY = SCH.servletContext.getRealPath("/")

            println "Path to files : " +PATH_TO_TEMP_FILES_DIRECTORY

            println "VOU TENTAR LIMPAR OS FICHEIROS do processo "
            String nomeTempFile = getFileName(proc)
            String nomeTempFileInput = nomeTempFile+"."+RUNNING_FILES_EXTENSION
            String nomeTempFileOutput = nomeTempFile+"."+PROCESSED_FILES_EXTENSION

            println "ficheiro : " + nomeTempFile

            File fileOutput = new File(nomeTempFileOutput)
            File fileInput = new File(nomeTempFileInput)

            if (fileInput.exists()) {
                println "Vou apagar "+fileInput.getName()
                fileInput.delete()
            }

            if (fileOutput.exists()) {
                println "Vou apagar "+fileOutput.getName()
                fileOutput.delete()
            }

    }




























}
